import appConfig from "@/appConfig";
import store from "@/store";
import msgUtils from "@/libs/msgUtils";
import utils from "@/libs/utils";
import statisticsEventUtils from "./statisticsEventUtils";

global.store = store
export default {
  async init() {
    try {
      await this.initEnv()
      await this.initData()
    } catch (e) {
      console.log(e)
    }
  },

  async initData(retry = 0, debug = 0) {
    uni.showLoading({
      title: retry ? ('重试中...' + retry) : '加载中...', mask: true
    })
    try {
      if (debug) {
        throw new Error('xx')
      }
      await store.dispatch('checkLogined')
      await store.dispatch('question/initUserData')
      if (store.getters.eventTime) {
        statisticsEventUtils.start(store.getters.eventTime)
      }
      if (store.getters.mine.vipExpiredStr) {
        msgUtils.publishMsg({
          type: 'vip_expired',
          confirmText: '续费开通',
          href: '/pages/vip/vip',
          content: '到期时间：' + store.getters.mine.vipExpiredStr
        })
      }
      uni.hideLoading()
    } catch (e) {
      console.log(e)
      uni.hideLoading()
      if (e.data && e.data.msg) {
        this.showBanModal(e.data.msg)
      } else {
        uni.showModal({
          title: '网络异常，请确认权限已打开！',
          content: '无法打开请微信/电话联系：15701313531',
          confirmText: '重试',
          cancelText: '复制电话',
          success: ({confirm, cancel}) => {
            if (confirm) {
              this.initData(retry + 1)
            } else if (cancel) {
              uni.setClipboardData({
                data: '15701313531', success: () => {
                  uni.showToast({
                    title: '电话复制成功！', icon: 'none', duration: 2000, success: () => {
                      setTimeout(() => {
                        this.initData(retry + 1)
                      }, 2000)
                    }
                  });
                }
              });
            }
          }
        })
      }
    }
  },

  showBanModal(msg) {
    uni.showModal({
      title: msg,
      success: ({confirm, cancel}) => {
        this.showBanModal(msg)
      }
    })
  },

  async initEnv() {
    console.log('initEnv start')
    await this.initSetting()

    uni.addInterceptor('navigateTo', {
      invoke: this.routerInterceptor
    })
    uni.addInterceptor('redirectTo', {
      invoke: this.routerInterceptor
    })

    store.dispatch('args/init')
    console.log('initEnv Finish')
  },

  initQuery(args) {
    // store.dispatch('initQuery', {query: Object.assign({inviter: 1239}, args.query)})
    // store.dispatch('initQuery', {query: Object.assign({inviter: 1239, schoolId: 32801}, args.query)})
    // store.dispatch('initQuery', {query: Object.assign({inviter: 1239, coachId: 1}, args.query)})
    store.dispatch('initQuery', {query: args.query})
  },

  async initSetting() {
    const env = getEnv()
    const debug = utils.initDebugStatus()
    if (env === 'develop') {
      appConfig.host = appConfig.develop
    } else {
      if (debug.status) {
        appConfig.host = debug.host
      } else {
        appConfig.host = appConfig.release
      }
    }
    appConfig.api = appConfig.host

    const res = await utils.getSystemInfo()
    res.debug = debug
    console.log('initSetting', env, res)
    await store.dispatch('initSetting', {env, systemInfo: res})
    store.dispatch('initCurrentTime')
  },

  routerInterceptor: (args) => {
    console.log('navigateTo', args.url, args, store.getters.isAllVIP)

    if (!store.getters.isAllVIP) {
      let needVip = appConfig.router.needVip.find(page => {
        // console.log('compare', args.url, page, args.url.indexOf(page))
        // 需要VIP
        if (args.url.indexOf(page) > -1) {
          return true
        }
        return false
      })
      console.log('needVip', needVip)
      if (needVip) {
        let gatewayUrl, from
        if (needVip === 'pages/shorthand/shorthand') {
          from = args.url
          gatewayUrl = '/pages/vip_gateway/vip_gateway?type=miji'
        } else if (needVip === 'pages/mijuan/mijuan') {
          from = args.url
          gatewayUrl = '/pages/vip_gateway/vip_gateway?type=mijuan'
        } else {
          if (needVip === 'pages/detail/detail') {
            if (args.url.indexOf('jingxuan') > -1) {
              from = args.url
              gatewayUrl = '/pages/vip_gateway/vip_gateway?type=jingxuan'
            } else if (args.url.indexOf('mijuan') > -1) {
            } else {
              needVip = null
            }
          }
        }
        let kemu = args.url.match(/kemu=\d/)
        if (kemu) {
          kemu = kemu[0]
        }
        // console.error('kemu', kemu)

        if (needVip) {
          let toUrl;
          if (gatewayUrl && store.getters.vipGateway !== 'all') {
            toUrl = gatewayUrl
            if (kemu) {
              toUrl += '&' + kemu
            }
            toUrl += '&from=' + encodeURIComponent(from)
          } else {
            toUrl = appConfig.router.toVip

            if (kemu) {
              toUrl += '?' + kemu
            }
          }

          if (kemu) {
            if (kemu === 'kemu=1') {
              if (!store.getters.isKemu1VIP) {
                args.url = toUrl
              } else {
                console.log('科目一VIP已开通')
              }
            } else if (kemu === 'kemu=2') {
              if (!store.getters.isKemu2VIP) {
                args.url = toUrl
              } else {
                console.log('科目二VIP已开通')
              }
            } else if (kemu === 'kemu=3') {
              if (!store.getters.isKemu3VIP) {
                args.url = toUrl
              } else {
                console.log('科目三VIP已开通')
              }
            } else if (kemu === 'kemu=4') {
              if (!store.getters.isKemu4VIP) {
                args.url = toUrl
              } else {
                console.log('科目四VIP已开通')
              }
            }
          }
        }
      }

      if (args.url.indexOf('pages/vip/vip') > -1) {
        args.animationType = 'slide-in-bottom'
        if (store.getters.appType === 3) {
          // args.url = '/pages/product_detail/product_detail?course_id=' + store.getters.fanzhishiVIPProductId
        }
      }
    }

    console.log('navigateToEnd', args.url)
  }
}

function getEnv() {
  let env;
  if (process.env.NODE_ENV === 'development') {
    env = 'develop'
  } else if (process.env.NODE_ENV === 'production') {
    env = 'release'
  }

  console.log('env', env)
  return env
}
